import 'package:pacsun/model/taskModel.dart';
import 'package:pacsun/utils/utils.dart';
import 'package:pacsun/view/create/mediaPicker/mediaPickerPage.dart';
import 'package:pacsun/view/task/theme/app_colors.dart';
import 'package:pacsun/view/task/widgets/cache_network_image.dart';
import 'package:pacsun/view/create/createBecomeCreator.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:pacsun/view/task/task_detail_page.dart';
import 'package:pacsun/view/user/userProfile.dart' show UserProfile;
import 'package:flutter_svg/svg.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:pacsun/utils/frontBottomSheet.dart'
    show showStoreFrontBottomSheet;

class TaskCard extends StatelessWidget {
  final int? index;
  const TaskCard(
      {super.key,
      required this.task,
      required this.type,
      this.fromType,
      this.index});

  final TaskModal task;
  final String type;

  final dynamic fromType;

  void jumpPage(context, bool isExpired) {
    // taskrecordid 任务到my Task 后的id
    // taskconfigid 任务原始id
    Widget page;
    // 新手任务并且已完成才提示
    if (task.status == 'ENDED' && task.taskType == 'BEGINNER_TASK') {
      Fluttertoast.showToast(
          msg: 'Completed',
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          backgroundColor: AppColors.toastBackground);
    } else if (task.taskCode == 'SET_CENTER_PAGE') {
      Fluttertoast.showToast(
          msg: 'Function under development',
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          backgroundColor: AppColors.toastBackground);
    } else if (isExpired) {
      Fluttertoast.showToast(
          msg: 'The Task Has Expired',
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          backgroundColor: AppColors.toastBackground);
      return;
    } else {
      switch (task.taskCode) {
        // 注册创作者
        case 'REGISTER_TASK':
          page = BecomeCreator(sourceIndex: 2);
          break;
        // 社媒主页添加社区主页
        // case 'ADD_COMMUNITY_HOMEPAGE':
        //   page = UserProfile(taskId: task.id);
        //   break;
        case 'ADD_COMMUNITY_HOMEPAGE':
          showStoreFrontBottomSheet(context, task.id);
          return; // Important to return here

        // 完善个人资料
        case 'SET_HOMEPAGE':
          page = UserProfile(taskId: task.id);
          break;
        // 发布第一个帖子
        case 'FIRST_PUBLISH':
          page = MediaPickerPage(taskConfigId: task.taskconfigid);
          break;
        default:
          page = TaskDetailPage(
            taskId: task.taskrecordid ?? task.id,
            taskType: task.taskrecordid != null ? 'My Tasks' : type,
          );
          break;
      }
      Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => page,
        ),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    final Color taskTypeBgColor = task.taskType == 'BEGINNER_TASK'
        ? Color(0xFF3DAC7C)
        : Color(0xFF4E63B2);

    String diffTimeStr = formatUSTimeDiff(task.endDate);
    bool isExpired = diffTimeStr.contains('-');
    return GestureDetector(
      onTap: () => {jumpPage(context, isExpired)},
      child: Container(
        margin: fromType == 1
            ? const EdgeInsets.only(bottom: 12)
            : const EdgeInsets.only(bottom: 12, right: 12),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(4).r,
          gradient: LinearGradient(
            colors: _getGradientColors(),
            stops: [0.0, 0.65],
            begin: Alignment.centerLeft,
            end: Alignment.centerRight,
          ),
        ),
        padding: EdgeInsets.all(12).r,
        child: Stack(
          clipBehavior: Clip.none,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                CacheNetworkImage(
                  imageUrl: task.bannerUrl,
                  width: 46.w,
                  height: 46.h,
                  borderRadius: 4.r,
                ),
                Expanded(
                  child: Padding(
                    padding: const EdgeInsets.only(left: 10).r,
                    child: Column(
                      children: [
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            Expanded(
                              child: SizedBox(
                                height: 46.h,
                                child: type == 'ACTIVE'
                                    ? _buildActiveCenter()
                                    : _buildMyCenter(),
                              ),
                            ),
                            type == 'ACTIVE'
                                ? _buildActiveRight()
                                // : _buildMyRight(diffTimeStr),
                                : isExpired && task.status != 'ENDED'
                                    ? const SizedBox.shrink()
                                    : _buildMyRight(diffTimeStr),
                          ],
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
            // type == 'ACTIVE' && task.taskType != 'CONTENT_TASK'
            task.taskType == 'BEGINNER_TASK'
                ? Positioned(
                    top: -12.h,
                    right: -12.w,
                    child: Container(
                      width: 57.w,
                      height: 20.h,
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                        color: taskTypeBgColor,
                        borderRadius: BorderRadius.only(
                          topRight: Radius.circular(4),
                          bottomLeft: Radius.circular(4),
                        ).r,
                      ),
                      padding:
                          EdgeInsets.only(top: 3, bottom: 3, right: 5, left: 5)
                              .r,
                      child: Text(task.taskTypeStr,
                          style: customTextStyle(fontSize: 10)),
                    ))
                : const SizedBox(),
            if (isExpired && task.status != 'ENDED')
              Positioned(
                right: -12.w,
                bottom: -12.h,
                child: SvgPicture.asset(
                  'assets/icons/icon_expired.svg',
                  width: 67.2.w,
                  height: 67.2.h,
                  color: Colors.white.withAlpha(70),
                ),
              )
          ],
        ),
      ),
    );
  }

  // Active 任务中间内容
  Widget _buildActiveCenter() {
    return Column(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(task.taskName,
            style: customTextStyle(
              fontSize: 14,
              overflow: TextOverflow.ellipsis,
              height: 1.2,
              fontWeight: 500,
            ),
            maxLines: 1,
            softWrap: true),
        // Text(
        //   task.description,
        //   style: customTextStyle(
        //       overflow: TextOverflow.ellipsis, opacity: 0.4, height: 1.4),
        //   maxLines: 1,
        // ),
        const SizedBox(height: 5),
        Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            task.platformIconUrl.isNotEmpty
                ? Padding(
                    padding: const EdgeInsets.only(right: 5),
                    child: Builder(
                      builder: (context) {
                        return CacheNetworkImage(
                          imageUrl: task.platformIconUrl,
                          imageType: ImageType.asset,
                          width: 12.w,
                          height: 12.h,
                          borderRadius: 4.r,
                        );
                      },
                    ),
                  )
                : const SizedBox.shrink(),
            Text(
              task.endDateStr,
              style: customTextStyle(opacity: 0.3),
            ),
          ],
        ),
      ],
    );
  }

  // Active 任务右侧内容
  Widget _buildActiveRight() {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        if (task.taskReward.isNotEmpty && task.taskReward['cmp'] != null) ...[
          Text('+${task.taskReward['cmp']}',
              style: customTextStyle(
                fontSize: 18,
                fontWeight: 600,
                color: task.taskReward['type'] == 'money'
                    ? FamilyTextColor.money
                    : FamilyTextColor.points,
              )),
          SizedBox(width: 6),
          SvgPicture.asset(
            task.taskReward['type'] == 'money'
                ? 'assets/icons/icon_money1.svg'
                : 'assets/icons/icon_points.svg',
            width: 16.w,
            height: 16.w,
          ),
        ]

        // if (task.contentRewardMap['trackingPoints'] != null)
        //   Transform.translate(
        //     offset: Offset(task.contentRewardMap['money'] != null ? 6 : 0, 0),
        //     child: Image.asset(
        //       "assets/imgs/points.png",
        //       width: 16,
        //       height: 16,
        //     ),
        //   ),
        // if (task.contentRewardMap['money'] != null)
        //   Transform.translate(
        //     offset: const Offset(0, 0),
        //     child: Image.asset(
        //       "assets/imgs/money.png",
        //       width: 16,
        //       height: 16,
        //     ),
        //   ),
      ],
    );
  }

  // My 任务右侧内容
  Widget _buildMyRight(String diffTimeStr) {
    return task.status == 'ENDED'
        ? SvgPicture.asset(
            'assets/icons/icon_task_flow_success.svg',
            width: 24.w,
            height: 24.h,
          )
        : Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              diffTimeStr != ''
                  ? Text('$diffTimeStr left',
                      style: customTextStyle(opacity: 0.3))
                  : const SizedBox.shrink(),
              SizedBox(width: 10.w),
              SvgPicture.asset(
                'assets/icons/icon_arrow.svg',
                width: 7.w,
                height: 13.h,
              )
            ],
          );
  }

  // My 任务中间内容
  Widget _buildMyCenter() {
    return Column(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          task.taskName,
          style: customTextStyle(
            fontSize: 14,
            height: 16 / 14,
            overflow: TextOverflow.ellipsis,
          ),
          maxLines: 1,
        ),
        // SizedBox(height: 3.h),
        if (task.status == 'ENDED' &&
            task.taskReward.isNotEmpty &&
            task.taskReward['cmp'] != null)
          Row(
            children: [
              Text('+${task.taskReward['cmp']}',
                  style: customTextStyle(
                    fontSize: 18,
                    fontWeight: 600,
                    color: task.taskReward['type'] == 'money'
                        ? FamilyTextColor.money
                        : FamilyTextColor.points,
                  )),
              SizedBox(width: 6),
              SvgPicture.asset(
                task.taskReward['type'] == 'money'
                    ? 'assets/icons/icon_money1.svg'
                    : 'assets/icons/icon_points.svg',
                width: 16.w,
                height: 16.w,
              ),
            ],
          ),
        if (task.status != 'ENDED')
          IntrinsicWidth(
            child: Container(
              padding: EdgeInsets.all(5).r,
              margin: EdgeInsets.only(top: 3).r,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(4).r,
                color: AppColors.taskSatusBg,
              ),
              child: Row(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  SvgPicture.asset(
                    'assets/icons/taskstate.svg',
                    width: 12.w,
                    height: 12.h,
                  ),
                  SizedBox(width: 6.w),
                  Expanded(
                    child: Text(
                      task.subStatusDesc,
                      // task.subStatus,
                      style: customTextStyle(
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                  )
                ],
              ),
            ),
          ),
      ],
    );
  }

  List<Color> _getGradientColors() {
    if (fromType == 0 || fromType == 1) {
      final int threshold = fromType == 0 ? 4 : 3;
      if (index != null && index! % threshold == 0) {
        return [AppColors.gradientStart4, AppColors.gradientEnd3];
      }
      if (index != null && index! % threshold == 1) {
        return [AppColors.gradientStart1, AppColors.gradientEnd3];
      }
      if (index != null && index! % threshold == 2) {
        return [AppColors.gradientStart2, AppColors.gradientEnd3];
      }
      if (index != null && index! % threshold == 3) {
        return [AppColors.gradientStart1, AppColors.gradientEnd3];
      }
    }
    switch (task.taskType) {
      case 'PRODUCT_TASK':
        return [AppColors.gradientStart1, AppColors.gradientEnd1];
      case 'BEGINNER_TASK':
        return [AppColors.gradientStart3, AppColors.gradientEnd3];
      default:
        return [AppColors.gradientStart2, AppColors.gradientEnd2];
    }
  }
}
